<?php

namespace Modules\Activity\Entities;

use Illuminate\Database\Eloquent\Builder;
use Modules\Core\Entities\BaseEntity as Model;

use Modules\Activity\Entities\TicketRecord;

use ThrowException;

class Ticket extends Model
{
    // 代付订单

    protected $guarded = [];
    protected $table = 'activity_tickets';

    static public $resourceName = '活动剩余参与次数';

    public function change($type, $total, $description, $options = [])
    {
        $newStock = $this->stock + ($type === 'in' ? 1 : -1) * $total;

        $newUseTotal = $this->used_total;
        if ($type === 'out') {
            $newUseTotal += $total;
        }

        if ($newStock < 0) {
            return false;
        }

        $this->update([
            'stock' => $newStock,
            'total' => $this->total + $total,
            'used_total' => $newUseTotal,
        ]);

        $record = TicketRecord::create([
            'user_id' => $this->user_id,
            'node_id' => $this->node_id,
            'node_type' => $this->node_type,
            'node_uuid' => $this->node_uuid,
            'type' => $type === 'in' ? 1 : 2,
            'total' => $total,
            'after_total' => $newStock,
            'description' => $description,
            'sub_type' => @$options['sub_type']
        ]);

        return $record;
    }

    // 添加次数
    static public function in($user, $node, $total, $description, $options = []) 
    {
        $ticket = Ticket::where([
            'user_id' => $user->id,
            'node_uuid' => $node->uuid
        ])->first();

        if (!$ticket) {
            $ticket = Ticket::create([
                'user_id' => $user->id,
                'node_id' => $node->id,
                'node_type' => $node->activityType,
                'node_uuid' => $node->uuid,
                'total' => 0,
                'stock' => 0,
                'reward_total' => 0,
                'buy_total' => 0,
                'used_total' => 0
            ]);
        }

        return $ticket->change('in', $total, $description, $options);
    }
    // 添加次数
    static public function out($user, $node, $total, $description, $options = []) 
    {
        $ticket = Ticket::where([
            'user_id' => $user->id,
            'node_uuid' => $node->uuid
        ])->first();

        if (!$ticket) {
            return false;
        }

        return $ticket->change('out', $total, $description, $options);
    }

    static public function getTotal($user, $node)
    {
        if (!$user) {
            return 0;
        }

        $ticket = Ticket::where([
            'user_id' => $user->id,
            'node_uuid' => $node->uuid
        ])->first();

        return @$ticket->stock ?: 0;
    }
}
